package com.automannn.springPractice.applicationContext.bean.lookup;

import com.automannn.springPractice.applicationContext.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * 注释配置应用程序作为ioc容器测试
 *
 * @author chenkh
 * @time 2021/8/20 11:35
 * @date 2022/08/03
 */
public class LazyBeanTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(LazyBeanTest.class);
        context.refresh();
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        objectProvider(context);
        objectProviderStream(context);
        context.close();
    }


    @Bean
    @Primary
    public String helloWorld() {
        return "hello world";
    }

    @Bean
    public String message() {
        return "hello message";
    }

    public static void objectProvider(AnnotationConfigApplicationContext context) {
        ObjectProvider<User> objectProvider = context.getBeanProvider(User.class);
        User user = objectProvider.getIfAvailable(User::createUser);
        System.out.println(user);
    }

    public static void objectProviderStream(AnnotationConfigApplicationContext context) {
        ObjectProvider<String> objectProvider = context.getBeanProvider(String.class);
        objectProvider.forEach(System.out::println);
    }
}
